package cn.hh.service.impl;


import cn.hh.course.domain.Course;
import cn.hh.god.IBuyClient;
import cn.hh.god.domain.Buy;
import cn.hh.mapper.BuyMapper;
import cn.hh.service.IBuyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BuyServiceImpl implements IBuyService {
    @Autowired
    private BuyMapper buyMapper;
    @Autowired
    private IBuyClient client;

    @Override
    @Transactional
    public void buy(Buy buy) {
        Long user_id = buy.getUser_id();
        Integer buy_count = buy.getBuy_count();
        // 传入的数据是userid、courseid和购买数量  需要调用course-server查询到课表信息，再根据数量设置pay价格
        Long course_id = buy.getCourse_id();
        // 去调用course-server，根据id查询出课表信息
        Course course = client.getById(course_id);
        System.out.println(course);
        // 根据需要购买的票数，判断票数是否充足
        Integer sale_count = course.getSale_count();
        if(sale_count <= buy_count){
            throw new RuntimeException("票数不足！");
        }
        // 计算出pay，保存购买信息
        buy.setPay_price(buy_count*course.getPrice());
        // 需要根据购买数量计算出pay_price
        buyMapper.buy(buy);
        // 购买成功之后再调用course-server，修改票数
        client.updateById(buy);
    }
}
